package com.sgzn.sgpay.service.impl;

import com.sgzn.sgpay.constants.Constants;
import com.sgzn.sgpay.enums.MchTypeEnum;
import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.exception.SgpayException;
import com.sgzn.sgpay.model.request.SgsMchPrivBatchAddRequest;
import com.sgzn.sgpay.model.request.SgsMchQueryListRequest;
import com.sgzn.sgpay.model.request.SgsRefreshPrivRequest;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.persistence.dao.TMerchantPrivMapper;
import com.sgzn.sgpay.persistence.dao.TMerchantPrivWriteMapper;
import com.sgzn.sgpay.persistence.dao.TPrivilegeMapper;
import com.sgzn.sgpay.persistence.domain.*;
import com.sgzn.sgpay.service.SgsMchPrivManageService;
import com.sgzn.sgpay.service.SgsMerchantQueryService;
import com.sgzn.sgpay.service.converter.PrivReqConverter;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import com.sgzn.sgpay.util.TranslateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商户权限管理服务
 * @author zhongzhongyong
 * @version Id: SgsMchPrivManageServiceImpl.java, v 0.1 2018/5/27 17:17 zhongzhongyong Exp $$
 */
@Service
@Slf4j
public class SgsMchPrivManageServiceImpl implements SgsMchPrivManageService {

    @Autowired
    private TPrivilegeMapper tPrivilegeMapper;

    @Autowired
    private TMerchantPrivWriteMapper tMerchantPrivWriteMapper;

    @Autowired
    private TMerchantPrivMapper tMerchantPrivMapper;

    @Autowired
    private SgsMerchantQueryService sgsMerchantQueryService;

    /**
     * 按照商户Id批量新增
     * @param request
     * @return
     */
    @Override
    public SgsResultResponse<String> batchInsertByMchId(SgsMchPrivBatchAddRequest request) {
        try{
            //获取权限id列表
            List<String> privIdList = getAllPrivId();
            if(CollectionUtils.isEmpty(privIdList)){
                throw new SgpayException(SgsResponseCode.C_PRIV_NOT_FOUND.getResponseCode(),SgsResponseCode.C_PRIV_NOT_FOUND.getResponseDesc());
            }
            //组装批量新增权限入参
            List<TMerchantPriv> params = PrivReqConverter.getBatchInsertMchPrivList(request.getMchId(),privIdList);
            //执行
            Map<String,Object> map = new HashMap<>();
            map.put("list",params);
            int num = tMerchantPrivWriteMapper.batchInsert(map);
            if(num > 0){
                return SgsResponseUtil.INSTANCE.success("success");
            }else{
                return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C_MCH_PRIV_BATCH_ADD_FAIL.getResponseCode(),SgsResponseCode.C_MCH_PRIV_BATCH_ADD_FAIL.getResponseDesc());
            }
        }catch (Exception e){
            log.error("商户权限批量新增失败.",e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C_MCH_PRIV_BATCH_ADD_FAIL.getResponseCode(),SgsResponseCode.C_MCH_PRIV_BATCH_ADD_FAIL.getResponseDesc());
        }
    }

    /**
     * 更新所有主商户的权限列表
     * @param request
     * @return
     */
    @Override
    public SgsResultResponse<String> refreshMainMchPriv(SgsRefreshPrivRequest request) {
        try{
            //获取所有主商户的商户ID集合
            List<String> mchIdList = getAllMainMchId(request);
            //获取权限id列表
            List<String> privIdList = getAllPrivId();
            if(CollectionUtils.isEmpty(privIdList)){
                throw new SgpayException(SgsResponseCode.C_PRIV_NOT_FOUND.getResponseCode(),SgsResponseCode.C_PRIV_NOT_FOUND.getResponseDesc());
            }
            //删除所有主商户的权限
            deleteAllMainMchPriv(mchIdList);
            //组装批量新增权限入参
            for(String mchId : mchIdList){
                List<TMerchantPriv> params = PrivReqConverter.getBatchInsertMchPrivList(mchId,privIdList);
                Map<String,Object> map = new HashMap<>();
                map.put("list",params);
                tMerchantPrivWriteMapper.batchInsert(map);
            }
            return SgsResponseUtil.INSTANCE.success("success");
        }catch (Exception e){
            log.error("商户权限批量新增失败.",e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C_MCH_PRIV_BATCH_ADD_FAIL.getResponseCode(),SgsResponseCode.C_MCH_PRIV_BATCH_ADD_FAIL.getResponseDesc());
        }
    }

    /**
     * 获取所有主商户的商户ID集合
     * @return
     */
    private List<String> getAllMainMchId(SgsRefreshPrivRequest request){
        List<String> mchIdList = new ArrayList<>();
        SgsMchQueryListRequest mchReq = new SgsMchQueryListRequest();
        mchReq.setInitiationID(request.getInitiationID());
        mchReq.setReqTime(request.getReqTime());
        mchReq.setLoginChannel(request.getLoginChannel());
        mchReq.setMchType(MchTypeEnum.MAIN_MERCHANT.getCode());
        SgsResultResponse<List<TMerchant>> mchQueryResp = sgsMerchantQueryService.queryMchBaseList(mchReq);
        if(TranslateUtil.isSuccessAbs(mchQueryResp.getErrorCode()) && !CollectionUtils.isEmpty(mchQueryResp.getResult())){
            List<TMerchant> mchList = mchQueryResp.getResult();
            for(TMerchant item : mchList){
                mchIdList.add(item.getMerchantId());
            }
        }
        return mchIdList;
    }

    /**
     * 获取权限id列表
     * @return
     */
    private List<String> getAllPrivId(){
        TPrivilegeExample example = new TPrivilegeExample();
        TPrivilegeExample.Criteria cra = example.createCriteria();
        cra.andPrivIdNotEqualTo(Constants.ROOT_PRIV_ID);//将根目录权限排除
        List<TPrivilege> privList =  tPrivilegeMapper.selectByExample(example);
        List<String> idList = new ArrayList<>();
        for(TPrivilege item : privList){
            idList.add(item.getPrivId());
        }
        return idList;
    }

    /**
     * 删除所有主商户的权限
     * @param mchIdList
     */
    private void deleteAllMainMchPriv(List<String> mchIdList){
        TMerchantPrivExample example = new TMerchantPrivExample();
        TMerchantPrivExample.Criteria cra = example.createCriteria();
        cra.andMchIdIn(mchIdList);
        tMerchantPrivMapper.deleteByExample(example);
    }

}
